package hamaster.jpbc.pbc;

import it.unisa.dia.gas.jpbc.Element;

import java.util.Properties;

public class PrivateKey implements Propertiable {

	private final static String RID_POSTFIX = "rid";
	private final static String HID_POSTFIX = "hid";

	protected Element rID;
	protected Element hID;

	public PrivateKey() {
	}

	public PrivateKey(Properties properties, String prefix) {
		setFromProperties(properties, prefix);
	}

	public Element getrID() {
		return rID;
	}

	public void setrID(Element rID) {
		this.rID = rID;
	}

	public Element gethID() {
		return hID;
	}

	public void sethID(Element hID) {
		this.hID = hID;
	}

	@Override
	public boolean setFromProperties(Properties properties, String prefix) {
		String rk = RID_POSTFIX;
		String hk = HID_POSTFIX;
		if (prefix != null && prefix.length() > 0) {
			rk = prefix + "." + RID_POSTFIX;
			hk = prefix + "." + HID_POSTFIX;
		}
		String rs = properties.getProperty(rk);
		String hs = properties.getProperty(hk);
		if (rs == null || hs == null)
			return false;
		PBC pbc = PBC.instance();
		rID = pbc.getPairing().getZr().newElement();
		hID = pbc.getPairing().getG2().newElement();
		rID.setFromBytes(PBCDriver.unhex(rs));
		hID.setFromBytes(PBCDriver.unhex(hs));
		return true;
	}

	@Override
	public Properties toProperties(String prefix) {
		Properties p = new Properties();
		String rk = RID_POSTFIX;
		String hk = HID_POSTFIX;
		if (prefix != null && prefix.length() > 0) {
			rk = prefix + "." + RID_POSTFIX;
			hk = prefix + "." + HID_POSTFIX;
		}
		p.setProperty(rk, PBCDriver.hex(rID.toBytes()));
		p.setProperty(hk, PBCDriver.hex(hID.toBytes()));
		return p;
	}

	@Override
	public String toString() {
		return "[PrivateKey]\nrID=" + rID + "\nhID=" + hID + "\n";
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		PrivateKey other = (PrivateKey) obj;
		if (hID == null) {
			if (other.hID != null)
				return false;
		} else if (!hID.equals(other.hID))
			return false;
		if (rID == null) {
			if (other.rID != null)
				return false;
		} else if (!rID.equals(other.rID))
			return false;
		return true;
	}

	@Override
	protected void finalize() throws Throwable {
		rID.setToRandom();
		hID.setToRandom();
		super.finalize();
	}

}
